package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * @author stone
 * @date 2022/11/14 10:52
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    PlatformTransactionManager transactionManager;

    @Override
    public void transfer(Integer fromId, Integer destId, Integer money) {
        // 开启事务 getTransaction
        TransactionStatus transactionStatus = transactionManager.getTransaction(TransactionDefinition.withDefaults());
        try {
            needTransaction(fromId, destId, money);
        } catch (Exception exception) {
            // 回滚事务 rollback
            transactionManager.rollback(transactionStatus);
            exception.printStackTrace();
        }
        // 提交事务 commit
        transactionManager.commit(transactionStatus);
    }

    @Override
    public void method2() {

        TransactionStatus transactionStatus = transactionManager.getTransaction(TransactionDefinition.withDefaults());
        try {
            System.out.println("hello world");
        } catch (Exception exception) {
            // 回滚事务 rollback
            transactionManager.rollback(transactionStatus);
            exception.printStackTrace();
        }
        // 提交事务 commit
        transactionManager.commit(transactionStatus);
    }

    private void needTransaction(Integer fromId, Integer destId, Integer money) {
        // 查询转出、接收方的钱
        Integer fromMoney = accountMapper.select(fromId);
        Integer destMoney = accountMapper.select(destId);

        // 计算转账成功，他两应该有多少钱
        fromMoney -= money;
        destMoney += money;

        // 根据id更新money
        accountMapper.update(fromId, fromMoney);

        int i = 1 / 0;

        accountMapper.update(destId, destMoney);//run
    }
}
